# /**
# * Copyright (c) 2022 Beijing Jiaotong University
# * PhotLab is licensed under [Open Source License].
# * You can use this software according to the terms and conditions of the [Open Source License].
# *
# * You may obtain a copy of [Open Source License] at: [https://open.source.license/]
# *
# * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# *
# * See the [Open Source License] for more details.
# */
# /**
# * Author: Shihao Xie
# * Created: Apr. 19, 2023
# * Supported by: National Key Research and Development Program of China
# */

import os
from phot_server.server_config.global_config import LIBRARY_ROOT
from phot_server.core.exception import FilePathError
from phot_server.utils.phot_file import is_subdir, get_absolute_path
from phot_server.utils.singleton import singleton
from phot_server.utils.phtc import parse_phtc, save_phtc
from phot_server.rpc.library_data_type.ttypes import PhotComponentPrototype


# save and read component prototype from file or sql
@singleton
class ComponentPrototypeRepository:
    """
    组件原型仓库
    """
    def __init__(self):
        pass

    # TODO: get component prototype from file and sqlite
    def get_component_prototype_from_file(self, path):
        if os.path.splitext(path)[-1] != ".phtc":
            path = path + ".phtc"
        if os.path.isabs(path):
            return parse_phtc(path)
        elif is_subdir(get_absolute_path(path, "library"),
                                         LIBRARY_ROOT) is False:
            raise FilePathError("Relative Path '{0}' is out of library root path."
                                .format(path))
        file_path = get_absolute_path(path, "library")
        return parse_phtc(file_path)

    def save_component_prototype_to_file(self, path, component: PhotComponentPrototype):
        if os.path.isdir(path):
            path = path + component.name
        if os.path.splitext(path)[-1] != ".phtc":
            path = path + ".phtc"
        if os.path.isabs(path) is False:
            save_phtc(self.fpath, component)
        else:
            save_phtc(path, component)

    def get_component_prototype_from_database(self, path):
        pass

    def save_component_prototype_to_database(self, path):
        pass
